package com.jinyu.admin.config;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.stp.StpInterface;
import com.jinyu.dao.mapper.sys.SysRoleMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: yangli
 * @Despriction: 获取当前账号权限码集合
 * @Package: com.jinyu.common.config
 * @Date:Created in 2022/5/5 21:57
 * @Modify By:
 */
@Slf4j
@Component
@Configuration
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest servletRequest = requestAttributes.getRequest();
        SaRequest request = SaManager.getSaTokenContext().getRequest();
        String pageId = servletRequest.getHeader("pageId");
        log.info("loginId = {};pageId = {}", loginId, pageId);
        //如果没传页面id则不做权限校验
        if (!StringUtils.hasText(pageId)) return null;
        //获取用户所有的角色集合
        List<String> roleCodeList = sysRoleMapper.getRoleListByUserCode((String) loginId);
        if (roleCodeList.size() < 1) return null;
        //通过用户角色集合以及pageId获取该用户对该页面的操作权限
        String permitCodes = sysRoleMapper.getPermitsByRoleCodeAndMenuId(roleCodeList, Long.parseLong(pageId));
        return Arrays.asList(permitCodes.split(","));
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        log.info("loginId = {};loginType = {}", loginId, loginType);
        return sysRoleMapper.getRoleListByUserCode((String) loginId);
    }
}
